#include <opencv2/opencv.hpp>
#include <iostream>
#include <chrono>

// g++ -o cv cv.cpp `pkg-config --cflags --libs opencv4`
int main(int argc, char **argv)
{
    if (argc < 2)
    {
        std::cout << "Usage: " << argv[0] << " <image file>" << std::endl;
        return (-1);
    }
    // 读取图像
    cv::Mat img = cv::imread(argv[1], cv::IMREAD_GRAYSCALE);
    if (img.empty())
    {
        std::cerr << "Error opening image!" << std::endl;
        return -1;
    }

    cv::Scalar meanVal = cv::mean(img);  
  
    // 注意：meanVal是一个Scalar对象，对于灰度图，我们只需要它的第一个元素  
    double mean = meanVal[0];
    printf("Image Mean: %f\n",mean);
    // 转换为二值图像（可选，取决于你的需求）
    cv::Mat binary;
    cv::threshold(img, binary, mean, 255, cv::THRESH_BINARY);

    // 计算开始时间

    // 查找轮廓
    std::vector<std::vector<cv::Point>> contours;
    cv::findContours(binary, contours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE); // 热启动一次

    std::chrono::duration<double> elapsed(0.0f);
    float time_cost=0.0f;
    for (int i = 0; i < 10; i++)
    {

        auto start = std::chrono::high_resolution_clock::now();
        cv::findContours(binary, contours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE);
        // 计算结束时间
        auto end = std::chrono::high_resolution_clock::now();
        elapsed = end - start;
        time_cost=time_cost+elapsed.count();
    }
    std::cout << "Contour finding took " << time_cost * 1000 / 10 << " ms." << std::endl;

    return 0;
}